<template>
  <div ref="draggable" id="draggable">
    <slot></slot>
    <!-- 插槽内容可以是按钮、图片等 -->
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const props = defineProps({
  container: {
    type: Object,
    required: false, // 传入外部定义的容器引用
    default: () => {},
  },
});

const draggable = ref(null);
let isDragging = false;
let shiftX = 0;
let shiftY = 0;

// 拖拽移动函数
const moveAt = (pageX, pageY) => {
  const containerRect = props.container?.getBoundingClientRect();
  const draggableRect = draggable.value.getBoundingClientRect();

  let newLeft = pageX - shiftX - containerRect?.left;
  let newTop = pageY - shiftY - containerRect?.top;

  // 限制 div 在容器内移动
  if (newLeft < 0) newLeft = 0;
  if (newTop < 0) newTop = 0;
  if (newLeft + draggableRect.width > containerRect?.width) {
    newLeft = containerRect.width - draggableRect.width;
  }
  if (newTop + draggableRect.height > containerRect?.height) {
    newTop = containerRect.height - draggableRect.height;
  }

  draggable.value.style.left = `${newLeft}px`;
  draggable.value.style.top = `${newTop}px`;
};

// 处理鼠标移动的逻辑
const onMouseMove = (event) => {
  if (isDragging) {
    moveAt(event.pageX, event.pageY);
  }
};

// 鼠标松开时停止拖拽
const onMouseUp = () => {
  if (isDragging) {
    document.removeEventListener('mousemove', onMouseMove);
    isDragging = false;

    // 恢复鼠标图标为 "move"
    draggable.value.style.cursor = 'move';
  }
};

onMounted(() => {
  draggable.value.onmouseenter = () => {
    draggable.value.onmousedown = (event) => {
      if (
        event.target.className === 'btn' ||
        event.target.className === 'zone-logo'
      ) {
        event.stopPropagation();
        return; // 点击了按钮，阻止拖拽
      }

      event.preventDefault(); // 阻止默认行为，避免图片等元素默认的拖拽行为
      isDragging = true; // 开始拖拽
      shiftX = event.clientX - draggable.value.getBoundingClientRect().left;
      shiftY = event.clientY - draggable.value.getBoundingClientRect().top;

      document.addEventListener('mousemove', onMouseMove);
      draggable.value.style.cursor = 'move'; // 设置鼠标图标为 'move'
    };
  };

  // 全局鼠标释放事件
  document.addEventListener('mouseup', onMouseUp);
});

// 清除事件监听器
onUnmounted(() => {
  document.removeEventListener('mousemove', onMouseMove);
  document.removeEventListener('mouseup', onMouseUp);
});
</script>

<style scoped>
#draggable {
  position: absolute;
  cursor: move;
  z-index: 999;
}
</style>
